'use client';

import React, { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { PageContainer } from '@ant-design/pro-components';
import { Button, Space, message, Card, Tabs, Form } from 'antd';
import { ArrowLeftOutlined, EditOutlined, SaveOutlined } from '@ant-design/icons';
import { UserInfo, UserRole, UserStatus } from '@/types/user';
import UserProfileForm from './components/UserProfileForm';
import UserSettingsForm from './components/UserSettingsForm';
import UserBillList from './components/UserBillList';

type PageMode = 'edit' | 'view';

const UserDetailPage: React.FC = () => {
  const params = useParams();
  const router = useRouter();
  const [form] = Form.useForm();
  const userId = params.id as string;
  
  const [mode, setMode] = useState<PageMode>('view');
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('profile');

  // 从 URL 参数中读取 tab
  useEffect(() => {
    const searchParams = new URLSearchParams(window.location.search);
    const tab = searchParams.get('tab');
    if (tab && ['profile', 'settings', 'bill'].includes(tab)) {
      setActiveTab(tab);
    }
  }, []);

  // 切换 tab 时更新 URL
  const handleTabChange = (tab: string) => {
    setActiveTab(tab);
    router.replace(`/users/${userId}?tab=${tab}`);
  };

  // 模拟用户数据
  const mockUserData: UserInfo = {
    id: userId,
    username: 'user001',
    phone: '18812341234',
    email: 'user001@example.com',
    realName: '李老师',
    role: UserRole.LEVEL_1_USER,
    status: UserStatus.NORMAL,
    balance: 1000,
    isVerified: true,
    createdAt: '2024-01-01 10:00:00',
    updatedAt: '2024-01-01 10:00:00',
  };

  useEffect(() => {
    const loadUserDetail = async () => {
      setLoading(true);
      try {
        // TODO: 调用API获取用户详情
        await new Promise(resolve => setTimeout(resolve, 500));
        setUserInfo(mockUserData);
        form.setFieldsValue(mockUserData);
      } catch {
        message.error('加载用户详情失败');
      } finally {
        setLoading(false);
      }
    };

    loadUserDetail();
  }, [userId, form]);

  // 表单提交
  const handleSubmit = async (values: Record<string, unknown>) => {
    setLoading(true);
    try {
      console.log('表单数据:', values);
      // TODO: 调用API保存数据
      await new Promise(resolve => setTimeout(resolve, 1000));
      message.success('更新成功');
      setMode('view');
    } catch {
      message.error('更新失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 切换到编辑模式
  const handleEdit = () => {
    setMode('edit');
  };

  // 获取操作按钮
  const getActionButtons = () => {
    if (mode === 'view') {
      return [
        <Button
          key="edit"
          icon={<EditOutlined />}
          onClick={handleEdit}
        >
          编辑
        </Button>
      ];
    }

    return [
      <Button 
        key="cancel" 
        onClick={() => {
          setMode('view');
          form.setFieldsValue(userInfo);
        }}
      >
        取消
      </Button>,
      <Button 
        key="save"
        type="primary" 
        loading={loading}
        icon={<SaveOutlined />}
        onClick={() => form.submit()}
      >
        保存
      </Button>
    ];
  };

  // Tab项配置
  const tabItems = [
    {
      key: 'profile',
      label: '基本信息',
      children: (
        <UserProfileForm 
          form={form}
          mode={mode}
          initialValues={userInfo || {}}
          onSubmit={handleSubmit}
        />
      ),
    },
    {
      key: 'settings',
      label: '用户设置',
      children: (
        <UserSettingsForm 
          form={form}
          mode={mode}
          initialValues={userInfo || {}}
          onSubmit={handleSubmit}
        />
      ),
    },
    {
      key: 'bill',
      label: '账单记录',
      children: (
        <UserBillList 
          userId={userId}
        />
      ),
    },
  ];

  if (loading && !userInfo) {
    return <PageContainer loading />;
  }

  return (
    <PageContainer
      title={
        <Space>
          <Button 
            type="text" 
            icon={<ArrowLeftOutlined />} 
            onClick={() => router.back()}
          >
            返回
          </Button>
          <span>用户详情</span>
          {userInfo && (
            <span style={{ fontSize: '16px', color: '#666' }}>
              - {userInfo.realName || userInfo.username}
            </span>
          )}
        </Space>
      }
      extra={
        <Space>
          {getActionButtons()}
        </Space>
      }
    >
      <Card>
        <Tabs
          activeKey={activeTab}
          onChange={handleTabChange}
          items={tabItems}
        />
      </Card>
    </PageContainer>
  );
};

export default UserDetailPage; 